$(function(){
	// 设置监测对象类型为 手术病例主要手术
//	paramTabPage[tabId].pType = "2" ;
	showCondition(true, 1, 0, 1,[]);//加载查询条件
	var param=drgUI.setAjaxData(tabId);
	loadOpeCaseAnalysisPage(param);

    $('#'+tabId+' input').iCheck({
        checkboxClass: 'icheckbox_square-blue',
        radioClass: 'iradio_square-blue',
        increaseArea: '20%' // optional
    });

    /**
     * 加载手术分析页面
     */
    function loadOpeCaseAnalysisPage(param){
        // 首次加载属性转换
        if(!(param.monitorType == "dep")) {
            param.monitorType = "hosp" ;
            param.ddesc = "全院" ;
        }
        // 更改描述
        if(param.ddesc) {
            $("#"+tabId+" .desc").text(param.ddesc);
        }
        // 加载模块1
        // 查询全院各手术级别统计信息
        $.post(contextPath+"/operationAnalysis/findOperationLevelAnalysis.dhc", param).done(function(result) {
            var data = result.data ;
            if(data[0] == undefined) {
                return ;
            }
            $("#"+tabId+" #remarks").html("注：监测时间段内<label>"+param.ddesc+"</label>出院病例数<label>"+formatNumber(data[0].TOTALCASECNT)+"</label>例，" +
                "主要手术病例<label>"+formatNumber(data[0].OPECASECNT)+"</label>例，手术例数占比<label>"+formatNumber(data[0].OPECASECNTR,2)+"%</label>。其中，三四级手术病例<label>"+formatNumber(data[0].THIRLEVEL+data[0].FOURLEVEL)+"</label>例，" +
                "三四级手术占比<label>"+formatNumber(data[0].THIRLEVELR+data[0].FOURLEVELR,2)+"%</label>");
            // 加载饼图
            var echartConfig = {
                "showLabel":true,
                "showLabelLine":true,
                radius:[0,"60%"],
                legendShow:false,
                clickFunc: function(param){
                    openOperationList(param.data.code,param.data.value);
                }
            };
            var opeLevelCaseDis = [] ;
            if(data && data[0]) {
                opeLevelCaseDis.push({name:"四级手术",value: data[0].FOURLEVEL,code: 4});
                opeLevelCaseDis.push({name:"三级手术",value:data[0].THIRLEVEL,code: 3});
                opeLevelCaseDis.push({name:"二级手术",value:data[0].SECLEVEL,code: 2});
                opeLevelCaseDis.push({name:"一级手术",value:data[0].FIRLEVEL,code: 1});
                opeLevelCaseDis.push({name:"其他",value:data[0].OPECASECNT-data[0].FIRLEVEL-data[0].SECLEVEL-data[0].THIRLEVEL-data[0].FOURLEVEL,code: 0});
            }
            pieCharts($("#"+tabId+" #operationLevelEchart"), opeLevelCaseDis, param.ddesc+"各手术级别病例分布图", "主要手术",echartConfig);
            // 手术级别病例统计表格数据
            // var tableData =  [] ;
            // if(data && data[0]) {
            //     tableData.push({"level":"四级手术","caseCnt":data[0].FOURLEVEL,"caseCntR":formatNumber(data[0].FOURLEVELR,2),"levelCode":4}) ;
            //     tableData.push({"level":"三级手术","caseCnt":data[0].THIRLEVEL,"caseCntR":formatNumber(data[0].THIRLEVELR,2),"levelCode":3}) ;
            //     tableData.push({"level":"二级手术","caseCnt":data[0].SECLEVEL,"caseCntR":formatNumber(data[0].SECLEVELR,2),"levelCode":2}) ;
            //     tableData.push({"level":"一级手术","caseCnt":data[0].FIRLEVEL,"caseCntR":formatNumber(data[0].FIRLEVELR,2),"levelCode":1}) ;
            //     tableData.push({"level":"其他","caseCnt":data[0].OPECASECNT-data[0].FIRLEVEL-data[0].SECLEVEL-data[0].THIRLEVEL-data[0].FOURLEVEL,"caseCntR":data[0].OPECASECNT == 0 ?0:formatNumber((data[0].OPECASECNT-data[0].FIRLEVEL-data[0].SECLEVEL-data[0].THIRLEVEL-data[0].FOURLEVEL)/data[0].OPECASECNT,2),"levelCode":0}) ;
            // }
            // 手术级别病例统计表格列定义
            // var columns=[
            //     {"data": "level","title":"手术级别"},
            //     {"data": "caseCnt","title":"手术例数"} ,
            //     {"data": "caseCntR","title":"手术病例数<br/>占比(%)","render": function(obj, type, full) {
            //             return formatNumber(full.caseCntR,2) ;
            //         }
            //     },
            //     {"data": "","title":"操作","render": function(obj, type, full) {
            //             return "<a href=\"javascript:openOperationList("+full.levelCode+","+full.caseCnt+")\" title=\"手术列表\"><i class=\"fa fa-list tdIcon\"></i></a>" ;
            //         }
            //     }
            // ] ;
            // var paramsDataTables={searching:false,lengthChange:true,ordering:false,stateSave:true,info:false,paging:false,tableTitle:"科室各手术级别下病例统计表",columnDefs:[]};
            // $("#"+tabId+" #operationLevelTable caption").html("<h5>"+param.ddesc+"各手术级别病例统计</h5>")
            // $("#"+tabId+" #operationLevelTable").dataTableBasic(columns,tableData,paramsDataTables) ;
        })

        // 根据当前监测类型加载模块二
        if(param.monitorType == "hosp") {
            // 查询科室各手术级别统计信息
            var paramdep=drgUI.setAjaxData(tabId);
            var chartTitle = '各科室不同手术级别下病例数分布图';
            paramdep.monitorType = "dep" ;
            $.post(contextPath+"/operationAnalysis/findOperationLevelAnalysis.dhc", paramdep ).done(function(result) {
                drawOperBarChart(result.data,chartTitle);
                loadOpeLevelCaseCountTable(result.data,"科室") ;
            })
        } else if(param.monitorType == "dep") {
            // 查询医师各手术级别统计信息
            $("#"+tabId+" #module2").text("医师") ;
            var paramDoc =  drgUI.setAjaxData(tabId);
            var chartTitle = paramDoc.ddesc+'各医师参与的不同手术级别下病例数分布图';
            paramDoc.monitorType = "doctor" ;
            $.post(contextPath+"/operationAnalysis/findDoctorOpeLevelAnalysis.dhc", paramDoc ).done(function(result) {
                drawOperBarChart(result.data,chartTitle);
                loadOpeLevelCaseCountTable(result.data,"手术医师") ;
            })
        }
    }
});


function drawOperBarChart(data,title){
	data = data || [];
	//排序
	data.sort(function(a,b){
		//按手术例数总和倒序
        return (b.FIRLEVEL+b.SECLEVEL+b.THIRLEVEL+b.FOURLEVEL)-(a.FIRLEVEL+a.SECLEVEL+a.THIRLEVEL+a.FOURLEVEL);
	});
	var category = [];
    var level1 = [];
    var level2 = [];
    var level3 = [];
    var level4 = [];
    for (var i = 0; i < data.length; i++) {
		var item = data[i];
		category.push(item.DDESC);
		level1.push(item.FIRLEVEL);
        level2.push(item.SECLEVEL);
        level3.push(item.THIRLEVEL);
        level4.push(item.FOURLEVEL);
    }
    var seriesData = [{
			name: '一级手术例数',
			type: 'bar',
			stack: '手术',
			data: level1
        },{
			name: '二级手术例数',
			type: 'bar',
			stack: '手术',
			data: level2
		},{
			name: '三级手术例数',
			type: 'bar',
			stack: '手术',
			data: level3
		},{
			name: '四级手术例数',
			type: 'bar',
			stack: '手术',
			data: level4
		}];
    var option = {
        title: {
            left: 'center',
            text: title
        },
        tooltip : {
            trigger: 'axis',
            axisPointer : {            // 坐标轴指示器，坐标轴触发有效
                type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        legend: {
            top: 25,
            data: ['四级手术例数', '三级手术例数','二级手术例数','一级手术例数']
        },
        grid: {
            left: '3%',
            right: '3%',
            containLabel: true
        },
        yAxis:  {
            type: 'value'
        },
        xAxis: {
            type: 'category',
            data: category,
            axisLabel: {
                interval: 0,
                rotate: -90
            }
        },
        series:seriesData
    };
    var myChart = echarts.init($("#"+tabId+" #operDeptBarChart")[0]);
	myChart.setOption(option);
}

/**
 * 不同手术级别病例统计
 * @param data
 * @param title
 */
function loadOpeLevelCaseCountTable(data,title) {
	var columns=[
	               	{"data": "DDESC","width":"80px","title":title,"render": function(obj, type, full) {
	               			if(title == "科室") {
		           				return "<a href=\"javascript:operationAnalysisDep('"+full.CCODE+"','"+full.DDESC+"') \">"+full.DDESC+"</a>" ;
	               			} else if(title == "手术医师") {
		           				return full.DDESC ;
	               			}
//           				return "<a href=\"javascript:operationAnalysisDep('"+full.CCODE+"','"+full.DDESC+"') \">"+full.DDESC+"</a>" ;
	           			}
	               	},
	               	{"data": "TOTALCASECNT","title":"病例数"},
	               	{"data": "OPECASECNT","title":"手术病例数" ,"render": function(obj, type, full) {
           					return "<a href=\"javascript:openOperationCaseDetail('"+full.CCODE+"','"+title+"')\" title=\"手术病例明细\">"+full.OPECASECNT+"</a>" ;
           				}
	               	},
	               	{"data": "OPECASECNTR","title":"手术病例数占比","render": function(obj, type, full) {
       						return formatNumber(full.OPECASECNTR,2) ;
       					}
	               	},
					{"data": "DOCTYPE","title":"","visible":false},
	               	{"data": "","title":"三四级手术例数","render": function(obj, type, full) {
           					return "<a href=\"javascript:openOperationCaseDetail('"+full.CCODE+"','"+title+"','3,4')\" title=\"手术病例明细\">"+(full.THIRLEVEL+full.FOURLEVEL)+"</a>" ;
           				}
	               	},
	               	{"data": "","title":"三四级手术例数占比(%)","render": function(obj, type, full) {
	   						return formatNumber(full.THIRLEVELR+full.FOURLEVELR,2) ;
	   					}
	               	},
	               	{"data": "FIRLEVEL","title":"一级手术例数" ,"render": function(obj, type, full) {
	           				return "<a href=\"javascript:openOperationCaseDetail('"+full.CCODE+"','"+title+"','1')\" title=\"手术病例明细\">"+full.FIRLEVEL+"</a>" ;
	           			}
	               	},
	               	{"data": "FIRLEVELR","title":"一级手术占比(%)" ,"render": function(obj, type, full) {
							return formatNumber(full.FIRLEVELR,2) ;
						}
	               	},
	               	{"data": "SECLEVEL","title":"二级手术例数" ,"render": function(obj, type, full) {
	           				return "<a href=\"javascript:openOperationCaseDetail('"+full.CCODE+"','"+title+"','2')\" title=\"手术病例明细\">"+full.SECLEVEL+"</a>" ;
	           			}
	               	},
	               	{"data": "SECLEVELR","title":"二级手术占比(%)","render": function(obj, type, full) {
							return formatNumber(full.SECLEVELR,2) ;
						}
	               	},
	               	{"data": "THIRLEVEL","title":"三级手术例数" ,"render": function(obj, type, full) {
	           				return "<a href=\"javascript:openOperationCaseDetail('"+full.CCODE+"','"+title+"','3')\" title=\"手术病例明细\">"+full.THIRLEVEL+"</a>" ;
	           			}
	               	},
	               	{"data": "THIRLEVELR","title":"三级手术占比(%)" ,"render": function(obj, type, full) {
   							return formatNumber(full.THIRLEVELR,2) ;
   						}
	               	},
	               	{"data": "FOURLEVEL","title":"四级手术例数" ,"render": function(obj, type, full) {
               				return "<a href=\"javascript:openOperationCaseDetail('"+full.CCODE+"','"+title+"','4')\" title=\"手术病例明细\">"+full.FOURLEVEL+"</a>" ;
               			}
	               	},
	               	{"data": "FOURLEVELR","title":"四级手术占比(%)" ,"render": function(obj, type, full) {
       						return formatNumber(full.FOURLEVELR,2) ;
       					}
	               	}/*,
	               	{"data": "","title":"操作","width":"80px","render": function(obj, type, full) {
	               			return "<a href=\"javascript:openOperationCaseDetail('"+full.CCODE+"','"+title+"')\" title=\"手术病例明细\"><i class=\"fa fa-users tdIcon\"></i></a>" ;
	               		}
	               	}*/
              ];
	var paramsDataTables={searching:true,lengthChange:true,ordering:true,order:[0],stateSave:false,info:false,scrollX:true,scrollY:'300px',autoWidth:false,orderCellsTop:true,tableTitle:"科室各手术级别下病例统计表",columnDefs:[{"orderable": true,"targets": [ 0 ] }]};
	// 如果统计的是医师，隐藏病例数和手术例数占比
	if(title=="手术医师") {
		paramsDataTables.columnDefs.push({ "visible": false, "targets": [1,3]}) ;
		$('#'+tabId+' #doctype').fadeIn();
	}
	var table = $("#"+tabId+" #operationLevelCaseTable").dataTableBasic(columns,data,paramsDataTables);
	//绑定手术医师类型多选框的change事件
    $('#'+tabId+' input').on('ifChanged',function(){
    	var regexStr = '[';//搜索用的正则表达式字符串
        $('#'+tabId+' #doctype input[name="doctype"]:checked').each(function(i,v){
        	regexStr += v.value;
		});
        regexStr += ']';
        //在第4列（医生类型）字段执行搜索
        table.column(4).search(regexStr,true).draw();
	});
}

/**
 * 科室钻取查看手术病例分析
 * @param depCode
 * @param depName
 */
function operationAnalysisDep(depCode,depName) {
	var param=drgUI.setAjaxData(tabId);
	param.monitorType = "dep" ;
	param.pardepCode = depCode ;
	param.ddesc = depName ;
	openTab('/pages/operationAnalysis/operationAnalysisHome.jsp', depName + "手术统计", "operationAnalysis_dep"+depCode , "operationAnalysis_dep"+depCode, param);
}

//保留n位小数并格式化输出（不足的部分补0）
//var fomatFloat = function(value, n) {
//	// 传入的非数字则直接返回
//	if(isNaN(value)) {
//		return value;
//	}
//	// 如果没有保留的位数，则默认保留小数点
//	if(!n && n!=0) {
//		n = 2 ;
//	}
//    var f = Math.round(value*Math.pow(10,n))/Math.pow(10,n);
//    var s = f.toString();
//    var rs = s.indexOf('.');   
//    if (rs < 0) {     
//        s += '.';   
//    } 
//    for(var i = s.length - s.indexOf('.'); i <= n; i++){
//      s += "0";
//    }
//    return s;
//}

/**
 * 手术列表
 * @param level 手术级别
 * @param casecnt 该级别手术病例数
 */
function openOperationList(level,casecnt) {
	$.post(contextPath + "/pages/common/top-dialog.jsp").done(function(data){
		var levelDesc = "" ;
		switch(level){
			case 1 : levelDesc = "一级手术" ; break ;
			case 2 : levelDesc = "二级手术" ; break ;
			case 3 : levelDesc = "三级手术" ; break ;
			case 4 : levelDesc = "四级手术" ; break ;
			default : levelDesc = "其他手术" ;
		}
		var dialog  = $(data);
		dialog.find(".modal-dialog").css("width","1000px");
		dialog.find("#echartcq4").css("width","960px");
		dialog.find("#echartcq4").css("height","360px");
		dialog.find(".modal-title").html(levelDesc+"列表");
		dialog.modal({
			keyboard: false,
			backdrop:"static"
		}).on({
			"hidden.bs.modal" : function(){
				$(this).remove();
			},
			"shown.bs.modal" : function(){
				dialog.find("#echartcq4").html("<table id=\"operationListTable\" class=\"cell-border\"></table>");
				dialog.find(".modal-body").append('<div style="margin-top: 30px">注：<br/><span style="display:block;margin-left: 20px;">1、同级别内例数占比（%） = 手术例数 / 该级别内手术总例数 * 100%</span><span style="display: inline-block;margin-left: 20px;">2、科室频次占比（%） = 科室手术频次 / 该手术例数 * 100%</span></div>') ;
				dialog.find(".modal-footer").css("margin-top","0px");
				var param=drgUI.setAjaxData(tabId);
				param.level = level ;
				$.post(contextPath+"/operationAnalysis/findOperationInfoByLevel.dhc", param ).done(function(result) {
					var columns=[
					             { "data": "RK",title:"序号",
					               		"render":function(data,type,full,meta){
					               			return full.RK ;
					               		}
					             },
					             { "data": "OPECODE",title:"手术编码"},
					             { "data": "OPEDESC",title:"手术名称" },
					             { "data": "OPER_LEVEL",title:"手术级别" },
					             { "data": "CNTOPE" ,title:"手术例数"},
					             { "data": "CNTINDEPR",title:"同级别例数占比(%)",render:function(obj, type, full){
					            	 	return formatNumber(full.CNTOPE/casecnt*100,2) ;
					             	}
					             },
					             { "data": "DEP_NAME" ,title:"科室分布"},
					             { "data": "CNTINDEP" ,title:"科室手术频次"},
					             { "data": "CNTINDEPR" ,title:"科室手术频次占比(%)",render:function(obj, type, full){
					            	 	return formatNumber(full.CNTINDEPR,2) ;
					             	}
					             },
				             ];
					
					//table加载完成后回调事件,合并单元格
					var drawCallback=function( oSettings ) {
						//封装的一个JQuery小插件,只合并手术编码相同的单元格，其他的行不做合并
						jQuery.fn.rowspannew = function(colIdx) { 
							return this.each(function(){ 
							var that; 
							$('tr', this).each(function(row) { 
							$('td:eq('+colIdx+')', this).filter(':visible').each(function(col) { 
							if (that!=null && $(this).html() == $(that).html()) { 
							rowspan = $(that).attr("rowSpan"); 
							if (rowspan == undefined) {
							$(that).attr("rowSpan",1); 
							rowspan = $(that).attr("rowSpan"); } 
							rowspan = Number(rowspan)+1; 
							$(that).attr("rowSpan",rowspan); 
							$(this).hide();
							//将前6列何必单元格
							$(that).parent("tr").find("td").eq(1).attr("rowSpan",rowspan); 
							$(that).parent("tr").find("td").eq(2).attr("rowSpan",rowspan); 
							$(that).parent("tr").find("td").eq(3).attr("rowSpan",rowspan); 
							$(that).parent("tr").find("td").eq(4).attr("rowSpan",rowspan); 
							$(that).parent("tr").find("td").eq(5).attr("rowSpan",rowspan); 
							//将多余的列进行移除
							for(var j=0;j<=4;j++){
								$(this).parent("tr").find("td").eq(1).remove();
							}
							} else {
							that = this; 
							}  }); }); });  }
						$(this).rowspannew(0);
				    };
				    
					var paramsDataTables={lengthChange:true,ordering:true,stateSave:false,info:false,columnDefs:[{"orderable": false,"targets": [ 0 ] }],tableTitle:levelDesc+"列表",scrollX:true,scrollY:'280px',autoWidth:false,orderCellsTop:true,pageLength:50,lengthMenu:[[ 50,100,500, 1000,99999],[ 50,100,500, 1000,'全部']]};
					paramsDataTables.drawCallback = drawCallback ;
					dialog.find("#echartcq4 #operationListTable").dataTableBasic(columns,result.data,paramsDataTables) ;
				})}
		});
 });
}

/**
 * 手术病例明细
 * @param id
 */
function openOperationCaseDetail(code,title,level) {
	var param=drgUI.setAjaxData(tabId);
//	param.monitorType = "dep" ;
	if(title =="科室") {
		param.pardepCode = code ;
	} else if(title =="手术医师") {
		param.doctorCode = code ;
	}
	param.opeLevel = level ;
	var tabTitle = "" ;
	switch(level) {
		case "1" : tabTitle = "一级" ;  break ;
		case "2" : tabTitle = "二级" ;  break ;
		case "3" : tabTitle = "三级" ;  break ;
		case "4" : tabTitle = "四级" ;  break ;
		case "3,4" : tabTitle = "三四级" ;  break ;
	}
	openTab('/pages/operationAnalysis/operationCaseDetail.jsp', tabTitle+"手术病例明细", "operationCaseDetail"+code , "operationCaseDetail"+code, param);
}